package castle.defense.project;

import android.content.Context;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
/**
 * Main thread for running the in game events.
 * 
 * @author Daniel Wasserman
 *
 */
public class GameThread extends Thread {
	private boolean running, paused;
	private SurfaceHolder sholder;
	private ObjectSet os;
	private long lastTime;
	private boolean started, gameover;
	private SoftButton sb;
	private long time, frames;

	public GameThread(SurfaceHolder sh, Context c)
	{
		this.setSurfaceHolder(sh);
		os = new ObjectSet();
		started = false;
		gameover = false;
		paused = true;
	}

	//Set a new SurfaceHolder
	public void setSurfaceHolder(SurfaceHolder h) {
		this.sholder = h;
	}

	public void setRunning(boolean r) { this.running = r; }
	public void setPaused(boolean p) {
		this.paused = p;
		if(!paused) {
			SoundManager.resumeBackground();
			lastTime = System.currentTimeMillis();
		} else {
			SoundManager.pauseBackground();
		}
	}
	public void inversePausedState() { setPaused(!paused); }

	@Override
	public void start()
	{
		if(!started)
		{
			started = true;
			setPaused(false);
			setRunning(true);
			super.start();
		}
	}

	//main function of the menu-thread
	@Override
	public void run()
	{
		time = 5000;
		frames = 0;
		//set castle here so the screen is for sure set.
		os.setCastle(new Castle("default", Options.getDifficulty() == Options.easy ? 1000 : Options.getDifficulty() == Options.medium ? 750 : 500, 0, 0));
		sb = new SoftButton(PE.regionByPercent(0, 15, 25, 15));
		sb.setTextOne("Test");
		while(running)
		{
			if(!paused)
			{
				long curTime = System.currentTimeMillis();
				
				time -= curTime - lastTime;
				if(time < 0) {
					System.out.printf("Frames = %d\nFPS = %.2f\n",frames,frames/5.0);
					frames = 0;
					time = 5000;
				}
				
				if(!gameover && os.collisionCheck()) {
					gameover = true;
					Options.score(Score.score);
				}
				if(!gameover) {
					os.update(curTime - lastTime);
				}
				
				lastTime = curTime;
				
				Canvas c = null;
				try {
					c = sholder.lockCanvas();
					synchronized(sholder) {
						doDraw(c);
					}
				} finally {
					if(c!=null)
						sholder.unlockCanvasAndPost(c);
				}
				frames++;
			}
			else
			{

			}
		}
	}


	//draw all of the objects onto the canvas
	private void doDraw(Canvas c)
	{
		if(c!=null) {
			GraphicsEngine.drawBackground(c);
			os.draw(c);
			Score.draw(c);
//			sb.draw(c);
			if(gameover) {
				GraphicsEngine.drawGameOverText(c);
			}
		}
	}

	public boolean onSingleTap(MotionEvent e) {
		if(!paused)
			os.onSingleTap(e);
		return true;
	}
}
